﻿namespace MockingBird.Simulator.Management
{
    using System.IO;
    public class FolderManager : IFolderManager
    {
        private ServiceConfigurationSettings configSettings;
        private string dataFilesRoot;
        private string endpointsRoot;
        private string currentEndpointFolder;

        public void CreateServiceFolders(ServiceConfigurationSettings targetConfigSettings)
        {
            this.configSettings = targetConfigSettings;
            this.CreateFolderTree();

        }

        public string GetConfigFolderRoot()
        {
            return this.CombinePaths(this.currentEndpointFolder, "config");

        }

        private void CreateFolderTree()
        {
            this.dataFilesRoot = Path.Combine(this.configSettings.SimulatorRoot, "datafiles");
            this.endpointsRoot = Path.Combine(dataFilesRoot, "endpoints");
            this.currentEndpointFolder = Path.Combine(endpointsRoot, this.configSettings.EndpointName);

            // the user may have created a folder set already
            if (configSettings.CreateServiceFolders)
            {
                CreateFolder(dataFilesRoot, "endpoints");
                CreateFolder(currentEndpointFolder, "config");
                CreateFolder(currentEndpointFolder, "requests");
                CreateFolder(currentEndpointFolder, "responses");
                CreateFolder(currentEndpointFolder, "metadata");
                CreateFolder(currentEndpointFolder, "logs");
                CreateFolder(Path.Combine(currentEndpointFolder, "logs"), "requests");
                CreateFolder(Path.Combine(currentEndpointFolder, "logs"), "responses");
            }
        }
        private static void CreateFolder(string baseFolder, string folderName)
        {
            if (!Directory.Exists(Path.Combine(baseFolder, folderName)))
            {
                Directory.CreateDirectory(Path.Combine(baseFolder, folderName));

            }
        }

        private string CombinePaths(params string[] folders)
        {
            string result = string.Empty;
            foreach (string entry in folders)
            {
                result = Path.Combine(result, entry);

            }

            return result;

        }

    }
}
